<?php
namespace app\api\model;
use think\Model;
use think\Log;
use think\Db;
use app\api\model\Student as StudentModel;
use app\api\model\Teacher as TeacherModel;
use app\common\lib\aes\IAuth;
use app\common\lib\aes\Aes;
use app\common\lib\exception\ApiException;

class User extends Model{
    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    protected $createTime = 'ctime';

    protected $updateTime = '';

    protected $dateFormat = 'Y-m-d H:i:s';

    /**
     * 自动对密码字段加密
     * @author 王柯 <wangke.email@foxmail.com>
     * @return string
     */
    public function setPasswordAttr($value)
    {
        return md5($value);
    }

    /**
     * 获取用户性别信息
     * @author 王柯 <wangke.email@foxmail.com>
     * @return mixed
     */
    public function getSexAttr($value){
        $sex = [
            0 => '男',
            1 =>'女',
        ];
        return $sex[$value];
    }

    /**
     * 获取用户停用状态
     * @author 王柯 <wangke.email@foxmail.com>
     * @return mixed
     */
    public function getStopStatusAttr($value){
        $stop_status = [
            0 => '已停用',
            1 => '已启用',
        ];
        return $stop_status[$value];
    }

    /**
     * 根据id获取用户信息
     * @param id int  用户id *必传
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|false|\PDOStatement|string|Model
     */
    public function read(){
        $data = $_GET;
        if(empty($data)) {
            throw new ApiException('数据不合法！',401);
        }

        if(!isset($data['id'])) {
            throw new ApiException('id is not found！',404);
        }

        try{
            $result = $this->alias('user')
                ->join('auth_group auth','user.user_auth=auth.id','LEFT')
                ->field('user.*,auth.title')
                ->where('user.id='.$data['id'])
                ->find();

            $obj = new Aes();
            $result->token = $obj->encrypt($result->token."||".$result->id);

            return show(config('code.success'),'ok！',$result);
        }catch (\Exception $e){
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(),400);
        }
    }

    /**
     * 新增会员
     * @param tel int 电话号码 *必传
     * @param password string 用户密码 *必传
     * @param user_auth int 用户权限 2教师 3学生 *必传
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|string|\think\response\Json
     */
    public function addUser(){

        $data = $_POST;
        if(empty($data)) {
            throw new ApiException('数据不合法！',401);
        }

        if(!isset($data['tel'])){
            throw new ApiException('tel is not found！',404);
        }

        if(!isset($data['user_auth'])){
            throw new ApiException('user_auth is not found！',404);
        }

        if(!isset($data['password'])){
            throw new ApiException('password is not found！',404);
        }

        Db::startTrans();//开启事务

        try{
            $data['ctime'] = time();
            $users = new User();
            $info = $users->where(array('tel'=>$data['tel']))->find();


            //验证
            $validate = validate('user');
            if(!$validate->scene('add_member')->check($data)){
                return show(config('code.error'),$validate->getError());
            }

            $data['password'] = md5($data['password']);

            if(empty($info)){
                if ($id = $users->insertGetId($data)) {
                    if($data['user_auth'] == 2){
                        $teacher = Db::name('teacher');
                        $tea['teacher_id'] = $id;
                        $res = $teacher->insertGetId($tea);

                        //设置登录token
                        $user = (new TeacherModel())->getTeacherInformation($id);

                        $token = IAuth::setAppLoginToken($user['tel']);
                        $data = [
                            'token' => $token,
                            //token过期时间
                            'time_out' => strtotime("+".config('app.login_time_out_day')." days"),
                        ];
                        $t_id = model('User')->save($data, ['tel' => $user['tel']]);
                        $obj = new Aes();
                        $user['token'] = $obj->encrypt($token."||".$t_id);
                        if($res){
                            Db::commit();//提交事务
                            return show(config('code.success'),'注册教师用户成功！',$user);
                        }else{
                            return show(config('code.error'),'注册教师用户失败！');
                        }
                    }else if($data['user_auth'] == 3){

                        $student = Db::name('student');
                        $stu['student_id'] = $id;
                        $stu['student_rank_id'] = 1;
                        $res = $student->insertGetId($stu);
                        $user = (new StudentModel())->getStudentInformation($id);
                        $token = IAuth::setAppLoginToken($user['tel']);
                        $data = [
                            'token' => $token,
                            //token过期时间
                            'time_out' => strtotime("+".config('app.login_time_out_day')." days"),
                        ];
                        $t_id = model('User')->save($data, ['tel' => $user['tel']]);
                        $obj = new Aes();
                        $user['token'] = $obj->encrypt($token."||".$t_id);
                        if($res){
                            Db::commit();//提交事务
                            return show(config('code.success'),'注册学生用户成功！',$user);
                        }else {
                            return show(config('code.error'), '注册学生会员失败！');
                        }
                    }
                }
            }elseif(!empty($info)){
                return show(config('code.error'), '手机号已注册！');
            }
        }catch (\Exception $e){
            Log::write($e->getMessage());
            Db::rollback();// 事务回滚
            throw new ApiException($e->getMessage(),500);
        }

    }

    /**
     * @param data array  修改的数据 *必传
     * @param id int  用户id *必传
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|string|\think\response\Json
     */
    public function edit(){
        $data = $_GET;

        if(empty($data)) {
            throw new ApiException('数据不合法！',401);
        }

        if(isset($data['id']) || isset($data['teacher_id']) || isset($data['student_id'])){

        }else{
            throw new ApiException('用户id is not found！',404);
        }

        try{
            $username = Db::name('user')->field('username')->select();

            $tel = Db::name('user')->field('tel')->select();

            if(!empty($data['username'])){
                foreach($username as $k => $v){
                    if(in_array($data['username'],$v))
                    {
                        return show(config('code.error'), '用户名已存在！');
                    }
                }
            }

            if(!empty($data['tel'])){
                foreach($tel as $k => $v){
                    if(in_array($data['tel'],$v)){
                        return show(config('code.error'), '手机号已注册！');
                    }
                }
            }

            if(isset($data['id'])){

                if(isset($data['pay_password'])){
                    $data['pay_password'] = md5($data['pay_password']);
                }

                if(isset($data['password'])){
                    $data['password'] = md5($data['password']);
                }

                $user = new User();

                $user->where('id='.$data['id'])->update($data);

                return show(config('code.success'), '修改成功！',$data);

            }

            if(isset($data['teacher_id'])){
                $teacher = new TeacherModel();
                $teacher->where('teacher_id='.$data['teacher_id'])->update($data);

                return show(config('code.success'), '修改成功！',$data);

            }

            if(isset($data['student_id'])){
                $student = new StudentModel();
                $student->where('student_id='.$data['student_id'])->update($data);

                return show(config('code.success'), '修改成功！',$data);

            }
        }catch (\Exception $e){
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(),500);
        }
    }

    /**
     * 获取用户数量
     * @author 王柯 <wangke.email@foxmail.com>
     * @return int|string
     */
    public function getUserCount(){
        try{
            $count = $this->field('id')->count();
            return show(config('code.success'),'ok！',$count);
        }catch (\Exception $e){
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(),400);
        }
    }

    /**
     * 修改用户密码
     * @param id int  用户id *必传
     * @param old_password string  用户原始密码 新用户可不传
     * @param password string  用户新密码 *必传
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|string|\think\response\Json
     */
    public function editUserPassword(){
        $data = $_POST;
        if(empty($data)) {
            throw new ApiException('数据不合法！',401);
        }

        if(!isset($data['id'])){
            throw new ApiException('id is not found！',404);
        }

        if(!isset($data['old_password'])){
            throw new ApiException('old_password is not found！',404);
        }

        $data['old_password'] = md5($data['old_password']);

        if(!isset($data['password'])){
            throw new ApiException('password is not found！',404);
        }

        try{
            $info = $this->where('id',$data['id'])
                ->field('password')
                ->find();
            if(!empty($info['password'])){

                if($info['password'] == $data['old_password']) {

                    if($data['old_password'] == md5($data['password'])){
                        return show(config('code.error'),'新密码与原始密码一致！');
                    }

                    unset($data['old_password']);

                    if (
                    $this
                        ->where('id='.$data['id'])
                        ->update(['password'=>md5($data['password'])])
                    ) {
                        return show(config('code.success'),'修改成功！');
                    } else {
                        return show(config('code.error'), '修改失败！');
                    }
                }else{
                    return show(config('code.error'), '原始密码不正确！');
                }
            }elseif(empty($info['password'])){
                if (
                $this->where('id='.$data['id'])
                    ->update(['password'=>$data['password']])
                ) {
                    return show(config('code.success'),'修改成功！');
                } else {
                    return show(config('code.error'), '修改失败！');
                }
            }
        }catch (\Exception $e){
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(),500);
        }
        throw new ApiException('未知错误！',500);
    }

    /**
     * @ 查询某人推荐的教师记录
     * @param id int 用户id 必传
     * @param status int 状态 必传 1查询推荐学生记录 2查询推荐教师记录
     * @author 巫玉梅 <1120504614@qq.com>
     * @return ApiException|array|string|\think\response\Json
     */
    public function recHistory(){
        $data = $_POST;
        if(empty($data)){
            throw new ApiException('数据不合法！',401);
        }
        //user_id 用户id 必传
        if(empty($data['id'])){
            throw new ApiException('id is not found！',404);
        }
        $where = array();
        if(empty($data['status'])){
            throw new ApiException('status is not found！',404);
        }else{
            if($data['status'] == 1){ //1查询推荐学生记录
                $where=array('rec_id'=>$data['id'],'user_auth'=>3);
            }elseif($data['status'] == 2){ //2查询推荐教师记录
                $where=array('rec_id'=>$data['id'],'user_auth'=>2);
            }
        }
        try{
            $info =Db::name('user')->where($where)->order('id desc')->select();

            return show(config('code.success'),'获取数据成功',$info,200);

        }catch(\Exception $e){
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(),400);
        }
    }






}